#!/usr/bin/env python
#-*- coding: utf-8 -*-
'''=========================
@Time : 2020/7/21 21:51
@Coder: xh
@IDE  : PyCharm
========================='''
import time
import json
import random
import hashlib
import tkinter
import requests


def get_post_data(e,r,i):
    str_sign = "fanyideskweb" + e + i + "mmbP%A-r6U3Nw(n]BjuEU"
    md = hashlib.md5()
    md.update(str_sign.encode())
    sign = md.hexdigest()
    data ={
    'i': e,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'salt': i,
    'sign': sign,
    'ts': r,
    'bv': '44a53b4124e8b822ebfd881c5a599938',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_CLICKBUTTION'
    }
    return data
def get_target():
    e = entry_1.get().strip()
    r = str(time.time()*1000)[:13]
    i = r + str(random.randint(0,9))
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    header = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
        'Cookie':'_ntes_nnid=9ecbee809cea3d51f42d55034abe3e67,1572154700538; OUTFOX_SEARCH_USER_ID_NCOO=966829990.111629; OUTFOX_SEARCH_USER_ID="1117076825@10.108.160.18"; P_INFO=y184xh; JSESSIONID=aaaH4UQ3nZOOA9eXNQXnx; ___rl__test__cookies=1595339878896',
        'Referer':'http://fanyi.youdao.com/'
    }
    data = get_post_data(e,r,i)
    response = requests.post(url,data=data,headers=header).text
    result = json.loads(response)['translateResult'][0][0]['tgt']
    content.set(result)

window = tkinter.Tk()
window.title('翻译')
window.wm_geometry('400x200+450+200')
#标签
label_1 = tkinter.Label(text='输入内容:',foreground='black',font=('楷体',16))
label_1.grid_configure(cnf={'row':0})
label2 = tkinter.Label(text='翻译结果:',foreground='black',font=('楷体',16))
label2.grid_configure(cnf={'row':1})
#文本框
entry_1 = tkinter.Entry(font=('楷体',15))
entry_1.grid_configure(cnf={'row':0,'column':1})
content = tkinter.StringVar()


entry_2 = tkinter.Entry(font=('楷体',15),textvariable=content)
entry_2.grid_configure(cnf={'row':1,'column':1})
#按钮
button_1 = tkinter.Button(text='翻译',font=('楷体',12),command=get_target)
button_1.grid_configure(cnf={'row':2,'column':0})
button_2 = tkinter.Button(text='退出',font=('楷体',12),command=quit)
button_2.grid_configure(cnf={'row':2,'column':1,'sticky':'E'})
window.mainloop()